#include "SocketIO.hpp"
#include <cerrno>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>


namespace wd
{
SocketIO::SocketIO(int fd)
    :_fd(fd)
{}

int SocketIO::readn(char *buf,int len){
    int size = len;
    char *p = buf;
    while(size){
        int ret = recv(_fd,p,size,0);
        if(ret ==-1 && errno == EINTR){
            continue;
        }else if(ret == -1){
            perror("read");
            return ret;
        }
        size -=ret;
        p +=ret;
    }
    return len;
}

int SocketIO::sendn(const char *buf,int len){
    int size = len;
    const char *p = buf;
    while(size){
        int ret = send(_fd,p,size,0);
        if(ret <0){
            return ret;
        }
        size -=ret;
        p+=ret;
    }
    return len;
}

int SocketIO::getline(char *buf,int max){
    //读到换行为止
    int size = max-1;
    char *p = buf;
    int total =0;

    while(size){
        int ret =recvPeek(p,size);

        for(int i =0;i<ret;i++){
            if(p[i] == '\n'){
                int size= i+1;
                ret = readn(p,size);
                if(ret <0){
                    /* perror("readn"); */
                    return ret;
                }
                p[i]='\0';
                total +=size;
                return total;
            }
        }//没有找到
        ret = readn(p,size);
        if(ret <0){
            perror("readn");
            return ret;
        }
        total +=ret;
        size -=ret;
        p+=ret;
    }

    buf[max-1] ='\0';
    return max-1;
}

int SocketIO::recvPeek(char *buf,int len)const{
    int ret =0;

    do{
        ret = recv(_fd,buf,len,MSG_PEEK);
    }while(ret ==-1 && errno == EINTR);

    if(ret <0){
        perror("recv(peek)");
    }
    return ret;
}

}//end of namespace
